﻿using System;
using Windows.Storage.Streams;
using System.Collections.Generic;
using Windows.Security.Cryptography;
using Windows.Security.Cryptography.Core;
using Windows.Security.Cryptography.DataProtection;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace eLuk.Security
{
	public class Encryption
	{
		public byte[] Encrypt( string text )
		{
			byte[] bytes = Encoding.UTF8.GetBytes( text );
			return this.Encrypt( bytes );
		}

		public byte[] Encrypt( byte[] content )
		{
			byte[] encrypted = null;
			IBuffer ibEncrypted;
			IBuffer ibDecrypted;
			IBuffer data = null;

			CryptographicKey key = this.GetKey();
			data = CryptographicBuffer.CreateFromByteArray( content );

			ibEncrypted = CryptographicEngine.Encrypt( key, data, null );
			ibDecrypted = CryptographicEngine.Decrypt( key, ibEncrypted, null );
			if ( !CryptographicBuffer.Compare( ibDecrypted, data ) )
			{
				//throw exception
			}
			CryptographicBuffer.CopyToByteArray( ibEncrypted, out encrypted );
			return encrypted;
		}

		private CryptographicKey GetKey()
		{
			String algName = "RSA_OAEP_SHA512";
			UInt32 keySize = 4096;
			CryptographicKey keyPair;
			// Create an AsymmetricKeyAlgorithmProvider object for the algorithm specified on input.
			AsymmetricKeyAlgorithmProvider Algorithm = AsymmetricKeyAlgorithmProvider.OpenAlgorithm( algName );
			// Generate a key pair.
			try
			{
				keyPair = Algorithm.CreateKeyPair( keySize );
			}
			catch ( ArgumentException ex )
			{
				return null;
			}
			return keyPair;
		}
	}
}
